package com.invoicerecognition.backend.service.impl.Invoice;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.invoicerecognition.backend.mapper.InvoiceMapper;
import com.invoicerecognition.backend.model.dto.Invoice;
import com.invoicerecognition.backend.model.dto.User;
import com.invoicerecognition.backend.service.Invoice.InfoService;
import com.invoicerecognition.backend.service.impl.utils.UserDetailsImpl;
import com.invoicerecognition.backend.utils.InvoiceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

import okhttp3.*;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

import java.net.URLEncoder;

@Service
public class InfoServiceImpl implements InfoService {

    @Autowired
    private InvoiceMapper invoiceMapper;

    @Override
    public JSONObject getInfoUrl(String imageData, String paramType) {

        InvoiceUtil invoiceUtil = new InvoiceUtil();
        String codeBase64 = "";
        try {
            codeBase64 = URLEncoder.encode(imageData, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        JSONObject result = invoiceUtil.getInvoice(codeBase64, paramType);

        return result;
    }

    @Override
    public JSONObject getInfoFile(MultipartFile file) {

        JSONObject res = new JSONObject();

        // 获取文件的 MIME 类型
        String mimeType = file.getContentType();
        // 将文件转换为字节数组
        byte[] fileBytes = null;
        try {
            fileBytes = file.getBytes();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 将字节数组编码为 Base64 字符串
        String imageData = Base64.getEncoder().encodeToString(fileBytes);
        // 根据 MIME 类型生成合适的 data:image/ 格式
        String imageUrl = "data:" + mimeType + ";base64," + imageData;

        InvoiceUtil invoiceUtil = new InvoiceUtil();
        // 这里是将Base64字符串再转换成百度云接口参数的格式
        String codeBase64 = "";
        try {
            codeBase64 = URLEncoder.encode(imageData, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        JSONObject result = invoiceUtil.getInvoice(codeBase64, "image");
        JSONObject invoiceInfo = (JSONObject) result.get("words_result");

        // 图片识别失败
        if (invoiceInfo == null) {
            res.put("error_message", "发票识别失败，请重新上传！");
            return res;
        }

        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

        UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal();
        User user = loginUser.getUser();
        int userId = user.getId();

        // 如果发票已经存在就不再存数据库
        String InvoiceNum = invoiceInfo.getString("InvoiceNum");
        QueryWrapper<Invoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("InvoiceNum", InvoiceNum)
                .eq("user_id", userId);
        List<Invoice> list = invoiceMapper.selectList(queryWrapper);
        if (!list.isEmpty()) {
            res.put("error_message", "发票已存在，请勿重复上传！");
            return res;
        }

        Invoice invoice = new Invoice();
        invoice.setUserId(userId);

        // 从 JSONObject 获取数据并转换为对应的 List<Map<String, String>> 类型
        invoice.setCommodityVehicleType(invoiceInfo.getString("CommodityVehicleType"));
        invoice.setCommodityNum(invoiceInfo.getString("CommodityNum"));
        invoice.setCommodityAmount(invoiceInfo.getString("CommodityAmount"));
        invoice.setCommodityPrice(invoiceInfo.getString("CommodityPrice"));
        invoice.setCommodityEndDate(invoiceInfo.getString("CommodityEndDate"));
        invoice.setCommodityStartDate(invoiceInfo.getString("CommodityStartDate"));
        invoice.setCommodityPlateNum(invoiceInfo.getString("CommodityPlateNum"));
        invoice.setCommodityUnit(invoiceInfo.getString("CommodityUnit"));
        invoice.setCommodityTax(invoiceInfo.getString("CommodityTax"));
        invoice.setCommodityName(invoiceInfo.getString("CommodityName"));
        invoice.setCommodityType(invoiceInfo.getString("CommodityType"));
        invoice.setCommodityTaxRate(invoiceInfo.getString("CommodityTaxRate"));

        // 你还可以填充其他的字段
        invoice.setPurchaserAddress(invoiceInfo.getString("PurchaserAddress"));
        invoice.setPurchaserBank(invoiceInfo.getString("PurchaserBank"));
        invoice.setPassword(invoiceInfo.getString("Password"));
        invoice.setSellerRegisterNum(invoiceInfo.getString("SellerRegisterNum"));
        invoice.setSellerBank(invoiceInfo.getString("SellerBank"));
        invoice.setInvoiceType(invoiceInfo.getString("InvoiceType"));
        invoice.setAmountInWords(invoiceInfo.getString("AmountInWords"));
        invoice.setTotalTax(invoiceInfo.getString("TotalTax"));
        invoice.setMachineCode(invoiceInfo.getString("MachineCode"));
        invoice.setCity(invoiceInfo.getString("City"));
        invoice.setInvoiceNumDigit(invoiceInfo.getString("InvoiceNumDigit"));
        invoice.setChecker(invoiceInfo.getString("Checker"));
        invoice.setInvoiceCode(invoiceInfo.getString("InvoiceCode"));
        invoice.setSellerAddress(invoiceInfo.getString("SellerAddress"));
        invoice.setNoteDrawer(invoiceInfo.getString("NoteDrawer"));
        invoice.setProvince(invoiceInfo.getString("Province"));
        invoice.setInvoiceNum(invoiceInfo.getString("InvoiceNum"));
        invoice.setServiceType(invoiceInfo.getString("ServiceType"));
        invoice.setInvoiceDate(invoiceInfo.getString("InvoiceDate"));
        invoice.setPurchaserRegisterNum(invoiceInfo.getString("PurchaserRegisterNum"));
        invoice.setTotalAmount(invoiceInfo.getString("TotalAmount"));
        invoice.setSheetNum(invoiceInfo.getString("SheetNum"));
        invoice.setPurchaserName(invoiceInfo.getString("PurchaserName"));
        invoice.setSellerName(invoiceInfo.getString("SellerName"));
        invoice.setInvoiceNumConfirm(invoiceInfo.getString("InvoiceNumConfirm"));
        invoice.setAgent(invoiceInfo.getString("Agent"));
        invoice.setInvoiceTag(invoiceInfo.getString("InvoiceTag"));
        invoice.setCheckCode(invoiceInfo.getString("CheckCode"));
        invoice.setInvoiceTypeOrg(invoiceInfo.getString("InvoiceTypeOrg"));
        invoice.setInvoiceCodeConfirm(invoiceInfo.getString("InvoiceCodeConfirm"));
        invoice.setRemarks(invoiceInfo.getString("Remarks"));
        invoice.setPayee(invoiceInfo.getString("Payee"));
        invoice.setAmountInFiguers(invoiceInfo.getString("AmountInFiguers"));
        invoice.setOnlinePay(invoiceInfo.getString("OnlinePay"));

        Date now = new Date();
        invoice.setCreatetime(now);
        invoice.setInvoicePhoto(imageUrl);

        // 保存到数据库
        invoiceMapper.insert(invoice);

        res.put("error_message", "上传成功！");
        return res;
    }

}
